package net.feling.hq711;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

import net.feling.hq711.Config;
import net.feling.hq711.view.GoodsGrid;
import net.feling.hq711.view.GoodsGrid.myLoadListener;
import net.feling.hq711.web.HttpFetcher;
import net.feling.hq711.web.XMLHandler;
import net.feling.hq711.web.Mail;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author chenyan@feling.net
 * 
 */
public class GoodslistActivity extends Activity implements
		NavigationDrawerFragment.NavigationDrawerCallbacks, myLoadListener {

	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private NavigationDrawerFragment mNavigationDrawerFragment;

	/**
	 * 在按返回键时使用的标记，使返回键是最小化，退出按钮才是退出
	 */
	private boolean exit = false;
	private boolean isloading_more_page = false;
	private boolean has_more_page = true;
	private static GoodsGrid goodsgrid = null;
	private Config config;
	private ProgressDialog progressdialog;

	/**
	 * 商品列表的页数
	 */
	private int page = 1;

	/**
	 * 商品的分类
	 */
	private int belongs = 1;

	/**
	 * Used to store the last screen title. For use in
	 * {@link #restoreActionBar()}.
	 */
	private CharSequence mTitle;

	public int getBelongs() {
		return belongs;
	}

	public void setBelongs(int belongs) {
		this.belongs = belongs;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_goodslist);

		mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		mTitle = getTitle();

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));
		config = (Config) getApplication();
		progressdialog = new ProgressDialog(this);
	}

	@Override
	public void onNavigationDrawerItemSelected(int position) {
		// update the main content by replacing fragments
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager
				.beginTransaction()
				.replace(R.id.container,
						PlaceholderFragment.newInstance(position + 1)).commit();
	}

	/**
	 * 根据分类和页数，获取列表数据，并调用setdata()
	 * 
	 * @param belongs
	 * @param page
	 */
	private void setGoodGrid(int belongs, int page) {
		String xmlString = "";
		String target_file = "";
		target_file = "class" + String.valueOf(belongs) + "_page"
				+ String.valueOf(page) + ".xml";
		// System.out.println(target_file);
		File file = new File(this.getFilesDir(), target_file);
		// 如果本地有对应分类的类表，且时间没过期,就直接读文件
		if (file.exists()
				&& System.currentTimeMillis() - file.lastModified() < 1 * 24 * 3600 * 1000) {
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(file));
				String line = null;
				while ((line = reader.readLine()) != null) {
					xmlString = xmlString + line;
				}
			} catch (IOException e) {
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e1) {
					}
				}
			}
			List<HashMap<String, String>> data = XMLHandler.execute(xmlString,
					"goods");
			goodsgrid.setData(data);
		} else {
			// 如果没有，就从网络获取,保存并显示
			String url = config.getServer() + target_file;
			new GoodsListXMLTask().execute(url);
		}

	}

	private class GoodsListXMLTask extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (getPage() == 1) {
				progressdialog.setMessage(getResources().getString(
						R.string.fetching_goodslist));
				progressdialog.setCancelable(false);
				progressdialog.show();
			}
		}

		@Override
		protected String doInBackground(String... params) {

			return new HttpFetcher().getString(params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			isloading_more_page = false;
			goodsgrid.loadComplete();
			if (getPage() == 1) {
				progressdialog.dismiss();
			}
			if (result == null) {
				if (getPage() - 1 > 0) {
					setPage(getPage() - 1);
				}
				Toast.makeText(GoodslistActivity.this, R.string.net_err,
						Toast.LENGTH_SHORT).show();
			} else if ("".equals(result)) {
				has_more_page = false;
				if (getPage() - 1 > 0) {
					setPage(getPage() - 1);
				}
				if (getPage() == 1 && goodsgrid.getCount()==0) {
					// System.out.println(getPage());
					Toast.makeText(GoodslistActivity.this, R.string.no_goods,
							Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(GoodslistActivity.this, R.string.no_more_goods,
							Toast.LENGTH_SHORT).show();
				}
			} else {
				has_more_page = true;
				List<HashMap<String, String>> data = XMLHandler.execute(result,
						"goods");
				if (data == null) {
					// XML解析异常（域名未备案，或服务端xml文件编辑出错）
					setPage(getPage() - 1);
					Toast.makeText(GoodslistActivity.this, R.string.xml_err,
							Toast.LENGTH_SHORT).show();
					String subject = getString(R.string.mail_subject_xml_err);
					String meg = getString(R.string.mail_subject_xml_err)
							+ "\n分类:" + mTitle + "\n页数:" + page;
					new Mail(GoodslistActivity.this, subject, meg).send_err();
				} else {
					if (getPage() == 1) {
						goodsgrid.setData(data);
					} else {
						goodsgrid.addData(data);
					}
				}
				// Toast.makeText(GoodslistActivity.this,
				// R.string.fetched_goodslist, Toast.LENGTH_SHORT).show();
				// TODO 保存文件,现在做成每次都更新商品列表，所以不保存
				// 也不做成检查服务器文件是否更新

			}

		}
	}

	public void onSectionAttached(int number) {
		// navigation选择后的动作，
		// 获取不同分类的商品列表；退出；进入个人信息界面
//		switch (number - 1) {
//		case 0:
//			mTitle = getString(R.string.app_name);
//			Intent intent = new Intent();
//			intent.setClass(GoodslistActivity.this, ProfileActivity.class);
//			startActivity(intent);
//			break;
		switch (number) {
		case 1:
			mTitle = getString(R.string.goods_class1);
			break;
		case 2:
			mTitle = getString(R.string.goods_class2);
			break;
		case 3:
			mTitle = getString(R.string.goods_class3);
			break;
		case 4:
			mTitle = getString(R.string.goods_class4);
			break;
		case 5:
			mTitle = getString(R.string.goods_class5);
			break;
		case 6:
			mTitle = getString(R.string.goods_class6);
			break;
		case 7:
			mTitle = getString(R.string.goods_class7);
			break;
		}
		if (number <= 7 && number >= 1) {
			setBelongs(number);
			setPage(1);
			try{//TODO 当这个activity在后台时，内存被清除了，这里会报空指针的错。
			setGoodGrid(getBelongs(), getPage());
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}

	public void restoreActionBar() {
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(mTitle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.goodslist, menu);
			restoreActionBar();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		// int id = item.getItemId();
		// if (id == R.id.action_settings) {
		// return true;
		// }
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";

		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static PlaceholderFragment newInstance(int sectionNumber) {
			PlaceholderFragment fragment = new PlaceholderFragment();
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
			return fragment;
		}

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_goodslist,
					container, false);
			goodsgrid = (GoodsGrid) rootView.findViewById(R.id.goods_grid);
			goodsgrid.setInterface((GoodslistActivity) getActivity());
			return rootView;
		}

		@Override
		public void onAttach(Activity activity) {
			super.onAttach(activity);
			((GoodslistActivity) activity).onSectionAttached(getArguments()
					.getInt(ARG_SECTION_NUMBER));
		}

	}

	@Override
	public void onBackPressed() {
		if (exit) {
			super.onBackPressed();
		} else {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addCategory(Intent.CATEGORY_HOME);
			startActivity(intent);
		}
	}

	@Override
	public void onLoadMore() {

//			if (has_more_page && !isloading_more_page) {
		if (!isloading_more_page){
				setPage(getPage() + 1);
				isloading_more_page = true;
				// System.out.println("loading  more");
				setGoodGrid(getBelongs(), getPage());
			}
//		}
	}

}
